#pragma once

// 套接字属性

#include <iostream>
#include <string>
#include <cstring>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"

enum{
    SOCKET_ERR = 1,
    BIND_ERR,
    LISTEN_ERR  
};

static const int backlog = 5;

class Sock
{
private:
    int sockfd_;
public:
    Sock()
    {}
    ~Sock()
    {}
public:
    // 1.创建套接字
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd_ < 0){
            lg(Fatal, "scoket create error");
            exit(SOCKET_ERR);
        }
        lg(Info, "socket create success...");
    }
    // 2.绑定套接字
    void Bind(uint16_t port)
    {
        // a.绑定预备工作
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        
        // b.开始绑定
        if(bind(sockfd_, (sockaddr*)&local, sizeof(local)) < 0){
            lg(Fatal, "socket bind eror");
            exit(BIND_ERR);
        }
        lg(Info, "socket bind success...");
    }
    // 3.监听套接字
    void Listen()
    {
        if(listen(sockfd_, backlog) < 0){
            lg(Fatal, "socket listen eror");
            exit(LISTEN_ERR);
        }
        lg(Info, "socket listen success...");
    }
    // 4.建立连接
    // 服务端用来 accept
    int Accept(std::string &clientip, uint16_t &clientport)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        size_t newfd = accept(sockfd_, (sockaddr*)&temp, &len);
        if(newfd < 0){
            lg(Warning, "accept error");
            return -1;
        }
        
        char ipstr[64];
        inet_ntop(AF_INET, &(temp.sin_addr), ipstr, sizeof(ipstr));
        clientip = ipstr;
        clientport = ntohs(temp.sin_port);

        return newfd;
    }
    // 客户端用来 connect
    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));

        int n = connect(sockfd_, (const sockaddr*)&peer, sizeof(peer));
        if(n < 0){
            std::cerr << "connect to "<< ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }
    // 5.关闭套接字
    void Close()
    {
        close(sockfd_);
    }
    // 6.获取套接字
    int Fd()
    {
        return sockfd_;
    }
};
